/**
 * 入口文件
 */ 
// 全局变量
var tankPlayer1 = new MyTank();
var staticImages = {};
/**
 * 预加载图片资源
 */
var sources = {
    'brickImage': 'stylesheet/image/Battle_City_bricks.png',
    'wallImage': 'stylesheet/image/Battle_City_wall.png',
    'baseImage': 'stylesheet/image/Battle_City_base.png',
    // 我方player1坦克的四个方向
    'tankPlayer1UpImage': 'stylesheet/image/Battle_City_Tank_Player1_Up.png',
    'tankPlayer1RightImage': 'stylesheet/image/Battle_City_Tank_Player1_Right.png',
    'tankPlayer1LeftImage': 'stylesheet/image/Battle_City_Tank_Player1_Left.png',
	'tankPlayer1DownImage': 'stylesheet/image/Battle_City_Tank_Player1_Down.png'
}

/*
 * 初始化
 */
function init(){
	loadImages(sources, function(images) {
		drawMap(images);
		drawTank(initMyTank());
	})
}

/*
 * 初始化我方tank
 */
function initMyTank() {
	tankPlayer1.x = 0;
	tankPlayer1.y = 576;
	tankPlayer1.face = 'tankPlayer1UpImage';
	// tankPlayer1.face = 'tankPlayer1RightImage';
	tankPlayer1.speed = 1;
	return tankPlayer1;
}


// 异步加载多张图片
// 原理: 异步加载每张图片，发现全部加载完成后(根据已加载图片数量和已知图片数量关系)再去绘图
function loadImages(sources, callback) {
	var images = {};
	var numImages = 0;
	var numLoadedImages = 0;

	for (var src in sources) {
		numImages++;
	}

	for (var src in sources) {
		images[src] = new Image();
		images[src].onload = function() {
			numLoadedImages++;
			if (numLoadedImages >= numImages) {
				// 全部加载完赋值
				staticImages = images;
				callback(images);
			}
		}
		images[src].src = sources[src];
	}
}

window.onload = init();
